//
//  RHNetManager.swift
//  RHYYSwiftProject
//
//  Created by Yoki on 2018/8/29.
//  Copyright © 2018年 Yoki. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class RHNetManager: NSObject {
    //单例
    static let share = RHNetManager()
    
    private var manager: Alamofire.SessionManager = {
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 10
        return Alamofire.SessionManager(configuration: configuration)

    }()


    typealias RHNetSuccessBlock = (NSDictionary) -> Void;
    typealias RHNetFaliedBlock  = (AFSErrorInfo) -> Void;
    typealias RHProgressBlock   = (Double) -> Void;
    
    ///Post请求
  func requestPost(url: String,param: Parameters?,successBlock:@escaping RHNetSuccessBlock, faliedBlock:@escaping RHNetFaliedBlock)  {
        let headers  : HTTPHeaders = ["Content-Type":"application/json;charset=utf-8"]; // http
        self.manager.request(url,method:HTTPMethod.post,parameters: param,encoding: URLEncoding.httpBody, headers: headers)
            .validate()
            .responseJSON(completionHandler: { (response) in
                self.handleResponse(response: response, successBlock: successBlock, faliedBlock: faliedBlock);
                
            });
        
    }
    /** 处理服务器响应数据*/
    
    private func handleResponse(response:DataResponse<Any>,successBlock:RHNetSuccessBlock,faliedBlock:RHNetFaliedBlock){
        
        if let error = response.result.error { // 服务器未返回数据
            
            self.handleRequestError(error: error as NSError, faliedBlock: faliedBlock);
            
        }else if let value = response.result.value { // 服务器又返回数据
            
            if (value as? NSDictionary) == nil { // 返回格式不对
                
                self.handleRequestSuccessWithFaliedBlcok(faliedBlock: faliedBlock)
                
            }else{
                
                self.handleRequestSuccess(value: value, successBlock: successBlock, faliedBlock: faliedBlock);//成功数据
                
            }
            
        }
        
    }
    
    /** 处理请求成功数据*/
    
    private func handleRequestSuccess(value:Any,successBlock:RHNetSuccessBlock,faliedBlock:RHNetFaliedBlock){
        successBlock(value as! NSDictionary);
        
        /**
         let json = JSON(value);
         
         if json["code"].int != nil && json["code"].int! == 1 { // 拦截
         
         successBlock(value as! NSDictionary,json);
         
         }else if json["code"].int != nil { // 获取服务器返回失败原因
         
         var errorInfo   = AFSErrorInfo01();
         
         errorInfo.code  = json["code"].int!;
         
         errorInfo.message = json["msg"].string != nil ? json["msg"].string! : "不认识的错误";
         
         faliedBlock(errorInfo);
         
         }
         ****/
    }
    
    /** 服务器返回数据解析出错*/
    
    private func handleRequestSuccessWithFaliedBlcok(faliedBlock:RHNetFaliedBlock){
        
        var errorInfo   = AFSErrorInfo();
        
        errorInfo.code  = -1;
        
        errorInfo.message = "数据解析出错";
        
    }
    
    /** 处理请求失败数据*/
    
    private func handleRequestError(error:NSError,faliedBlock:RHNetFaliedBlock){
        
        var errorInfo   = AFSErrorInfo();
        
        errorInfo.code  = error.code;
        
        errorInfo.error = error;
        
        if ( errorInfo.code == -1009 ) {
            
            errorInfo.message = "无网络连接";
            
        }else if ( errorInfo.code == -1001 ){
            
            errorInfo.message = "请求超时";
            
        }else if ( errorInfo.code == -1005 ){
            
            errorInfo.message = "网络连接丢失(服务器忙)";
            
        }else if ( errorInfo.code == -1004 ){
            
            errorInfo.message = "服务器没有启动";
            
        }else if ( errorInfo.code == 404 || errorInfo.code == 3){
            
            
            
        }
        
        faliedBlock(errorInfo);
        
    }
    
    
    
    /** 访问出错具体原因 */
    
    struct AFSErrorInfo {
        
        var code    = 0
        
        var message = ""
        
        var error   = NSError();
        
    }

}


   

